﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CuaHangMayTinh.BusinessEntities;
using CuaHangMayTinh.BusinessLogicLayer;
using CuaHangMayTinh.Utilities;
using DevComponents.DotNetBar.Controls;
using Microsoft.VisualBasic;

namespace CuaHangMayTinh.PresentationLayer
{
    public partial class FormBaoHanhSuaChua : Form
    {
        /// <summary>
        /// hiển thị list tên nhà cung cấp 
        /// </summary>
        private List<string> tenkhachhang = new List<string>();

        /// <summary>
        /// tạo đối tượng lusu trữ khách hàng
        /// </summary>
        private KhachHangEntity khachHangEntity;

        MatHangEntity matHangEntity = new MatHangEntity();

        BaoHanhSuaChuaEntity baoHanhSuaChuaEntity = new BaoHanhSuaChuaEntity();

        BaoHanhSuaChuaEntity BHentity = new BaoHanhSuaChuaEntity();

        /// <summary>
        /// tạo đối tượng lưu trữ lỗi 
        /// </summary>
        private string Text = string.Empty;

        public FormBaoHanhSuaChua()
        {
            InitializeComponent();
        }

        public FormBaoHanhSuaChua(BaoHanhSuaChuaEntity entity):this()
        {
            BHentity = entity;
            txt_tinhtrangtra.Enabled = true;
            btn_thanhtoan.Enabled = true;
            txt_tongtien.Enabled = true;
            SetEntity(entity);
            btn_luutru.Enabled = false;
        }

        /// <summary>
        /// bắt sự kiện thay đổi khách hàng
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBoxEx_khachhang_SelectedIndexChanged(object sender, EventArgs e)
        {
            cbb_khachhang.Text = "...";
            ComboBoxEx ex = sender as ComboBoxEx;
            DataRowView row = (DataRowView)ex.SelectedItem;
            khachHangEntity = KhachHangManager.ConvertToList(KhachHangManager.Find_ID((int)row[0]))[0];
            SetKhachHangEntity(row);
            EnableKhachHang(false);
            LoadMatHang();
        }

        /// <summary>
        /// tạo autocomple cho khách hàng
        /// </summary>
        /// <param name="dt"></param>
        private void SetAutoCompleKhachHang(DataTable dt)
        {
            if (dt != null)
            {
                foreach (DataRow row in dt.Rows)
                {
                    tenkhachhang.Add(row[1].ToString());
                }
            }
            txt_ten.AutoCompleteCustomSource.AddRange(tenkhachhang.ToArray());
        }

        /// <summary>
        /// hiển thị hoặc khóa nhập khách hàng
        /// </summary>
        /// <param name="i"></param>
        private void EnableKhachHang(bool i)
        {
            txt_cmnd.Enabled = i;
            txt_diachi.Enabled = i;
            txt_sodienthoai.Enabled = i;
        }

        /// <summary>
        /// lấy datarowview chuyển lên form
        /// </summary>
        /// <param name="row"></param>
        private void SetKhachHangEntity(DataRowView row)
        {
            txt_ten.Text = row[1].ToString();
            txt_cmnd.Text = row[2].ToString();
            txt_diachi.Text = row[4].ToString();
            txt_sodienthoai.Text = row[5].ToString();
        }

        /// <summary>
        /// bắt sự kiện load form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormBaoHanhSuaChua_Load(object sender, EventArgs e)
        {
            LoadKhachHangToCbb();
            dtime_ngaylap.Value = DateTime.Now;
            dtime_ngaytra.MinDate = DateTime.Now;
            dtime_ngaytra.Value = DateTime.Now;
            EnableKhachHang(false);
            Set_txtMaHD();
        }

        /// <summary>
        /// load khach hang lên combobox
        /// </summary>
        private void LoadKhachHangToCbb()
        {
            DataTable dt = DataUtil.ChangeColumn(KhachHangManager.Find_All());
            cbb_khachhang.DataSource = dt;
            cbb_khachhang.DisplayMember = "Tên khách hàng";
            cbb_khachhang.DropDownColumns = "Tên khách hàng,CMND-Mã số thuế,Số điện thoại,Địa chỉ";
            cbb_khachhang.DropDownWidth = 400;
            SetAutoCompleKhachHang(dt);
            EnableKhachHang(false);
        }

        private void LoadMatHang()
        {
            DataRowView row = (DataRowView)cbb_khachhang.SelectedItem;
            var dt2 = MatHangManager.Find_MaKhachHang((int)row[0],true);
            var dt = dt2.AsEnumerable().Where(x => x.Field<int>("TinhTrang") == 1).CopyToDataTable();
            if (dt.Rows.Count > 0)
            {
                cbb_mathang.DataSource = dt;
                cbb_mathang.ValueMember = "MaMH";
                cbb_mathang.DisplayMember = "Serial_Code";
            }
            EnableControl(dt.Rows.Count>0);
        }

        private void EnableControl(bool i)
        {
            cbb_mathang.Enabled = i;
            txt_ghichu.Enabled = i;
            dtime_ngaytra.Enabled = i;
            checkBox_suachua.Enabled = i;
            txt_tinhtrangnhan.Enabled = i;
        }

        private void SetEntity(BaoHanhSuaChuaEntity entity)
        {
            cbb_mathang.SelectedValue = entity.MaMH;
            txt_ghichu.Text = entity.GhiChu;
            dtime_ngaytra.Value = entity.NgayHenTra;
            checkBox_suachua.Checked = entity.BH_SC;
            txt_tinhtrangnhan.Text = entity.TinhTrangNhan;
        }


        private void SetMatHang(DataRow row)
        {
            txt_model.Text = (string)row[1];
            txt_hangsx.Text = (string)row[4];
            txt_cauhinh.Text = (string)row[6];
            txt_baohanh.Text = ((int)row[7]).ToString();
            DataTable dt = MatHangManager.Find_ID((int)row[0], false);
            if (!(dt.Rows[0][5] is int))
                dt.Rows[0][5] = 0;
            if (!(dt.Rows[0][2] is int))
                dt.Rows[0][2] = 0;
            if (!(dt.Rows[0][3] is int))
                dt.Rows[0][3] = 0;
            if (!(dt.Rows[0][4] is int))
                dt.Rows[0][4] = 0;
            matHangEntity = MatHangManager.ConvertToList(dt)[0];
        }

        private void comboBoxEx_mathang_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBoxEx ex = sender as ComboBoxEx;
            DataRowView row = (DataRowView)ex.SelectedItem;
            DataTable dt = MatHangManager.Find_ID((int)row[0], true);
            SetMatHang(dt.Rows[0]);
        }

        private void button_luutru_Click(object sender, EventArgs e)
        {
            var form = (FormChinh)this.MdiParent;
            baoHanhSuaChuaEntity = new BaoHanhSuaChuaEntity(txt_maphieunhap.Text, checkBox_suachua.Enabled,
                form.NhanVien.MaNV, khachHangEntity.MaKH, matHangEntity.MaMH, dtime_ngaylap.Value,
                dtime_ngaytra.Value, dtime_ngaylap.Value, txt_tinhtrangnhan.Text, txt_tinhtrangtra.Text,
                true, 0, txt_ghichu.Text);
            baoHanhSuaChuaEntity.mathang = matHangEntity;
            if (BaoHanhSuaChuaManager.InsertTS(baoHanhSuaChuaEntity, ref Text) > 0)
            {
                MessageBox.Show("Đã lưu phiếu bảo hành sửa chữa");
                EnableControl(false);
            }
            else
            {
                MessageBox.Show(Text);
            }
        }

        private void textBoxX_ten_Leave(object sender, EventArgs e)
        {
            if (!tenkhachhang.Contains(txt_ten.Text))
            {
                txt_ten.Focus();
            }
        }

        void Set_txtMaHD()
        {
            DataTable dt;
            txt_maphieunhap.Enabled = false;
            dt = BanHangManager.GetMaHDMax();
            string nam = DateTime.Now.Year.ToString().Substring(1, DateTime.Now.Year.ToString().Length - 1);
            if (dt.Rows.Count == 0)
            {
                txt_maphieunhap.Text = nam + "-0000001";
                return;
            }
            string mahd = dt.Rows[0][0].ToString();
            string[] temp = mahd.Split('-');
            if (temp[0].CompareTo(nam) != 0)
            {
                txt_maphieunhap.Text = nam + "-0000001";
                return;
            }
            int duoi = 0;
            string Duoi = "";
            if (temp[0].CompareTo(nam) == 0)
            {
                mahd = "";
                duoi = (int.Parse(temp[1]) + 1);
                if (duoi < 10)
                    Duoi = "-000000" + duoi;
                else
                    if (duoi < 100)
                        Duoi = "-00000" + duoi;
                    else
                        if (duoi < 1000)
                            Duoi = "-0000" + duoi;
                        else
                            if (duoi < 10000)
                                Duoi = "-000" + duoi;
                            else
                                if (duoi < 100000)
                                    Duoi = "-00" + duoi;
                mahd = temp[0] + Duoi;
                txt_maphieunhap.Text = mahd;
            }
        }

        private void buttonX_thanhtoan_Click(object sender, EventArgs e)
        {
            baoHanhSuaChuaEntity = BHentity;
            baoHanhSuaChuaEntity.TinhTrangTra = txt_tinhtrangtra.Text;
            baoHanhSuaChuaEntity.TongTien = Convert.ToDecimal(txt_tongtien.Text);
            baoHanhSuaChuaEntity.NgayTraHang = DateTime.Now;
            DataTable dtmathang = MatHangManager.Find_ID(baoHanhSuaChuaEntity.MaMH, false);
            dtmathang.Rows[0][4] = 0;
            baoHanhSuaChuaEntity.mathang =
                MatHangManager.ConvertToList(dtmathang)[0];
            if (BaoHanhSuaChuaManager.Update_DaTraHang(baoHanhSuaChuaEntity))
            {
                MessageBox.Show("Đã lưu phiếu bảo hành sửa chữa");
                EnableControl(false);
                txt_tinhtrangtra.Enabled = false;
                btn_thanhtoan.Enabled = false;
                txt_tongtien.Enabled = false;
            }
            else
            {
                MessageBox.Show(Text);
            }
        }

        private void toolStripbtn_taomoi_Click(object sender, EventArgs e)
        {
            FormBaoHanhSuaChua_Load(null,null);
        }

    }
}
